################################################################################
#* Project - Strength in Numbers? Gender Composition, Leadership, and Women’s Influence in Teams?
#* Researchers:  Christopher F. Karpowitz, Stephen D. O’Connell, Jessica Preece, and Olga Stoddard
#* Purpose: Install all R library needed to replicate "Strength in Numbers? Gender Composition, Leadership, and Women’s Influence in Teams?"
#* Created on: 10/16/2023
#* Last edited: 10/16/2023
#* Edits history:
################################################################################

# Identify all source code files in (sub)folders
files <- list.files(pattern='[.](R|rmd)$', all.files=T, recursive=T, full.names = T, ignore.case=T)

# Extract the source code
code = unlist(sapply(files, scan, what = 'character', quiet = TRUE))

# Filter out only source code that starts with the library command
code <- code[grepl('^library', code, ignore.case=T)]
code <- gsub('^library[(]', '', code)
code <- gsub('[)]', '', code)
code <- gsub('^library$', '', code)
code <- gsub('["\']', '', code)  # Remove quotation marks

# Retain only unique package names and trim any white spaces
uniq_packages <- unique(trimws(code))

# Remove any "empty" package names
uniq_packages <- uniq_packages[!uniq_packages == '']

# Create a blacklist of packages to exclude
blacklist <- c("library,", "parallel")

# Exclude packages from the blacklist
uniq_packages <- setdiff(uniq_packages, blacklist)

# Organize the list alphabetically
uniq_packages <- uniq_packages[order(uniq_packages)]

cat('Required packages: \n')
cat(paste0(uniq_packages, collapse= ', '), fill=T)
cat('\n\n\n')

# Fetch the list of currently installed packages
installed_packages <- installed.packages()[, 'Package']

# Check availability of packages for the current R version
available_packages <- rownames(available.packages(repos = 'https://cloud.r-project.org'))
to_be_installed <- setdiff(intersect(uniq_packages, available_packages), installed_packages)

if (length(to_be_installed) == length(uniq_packages)) {
  cat('All packages need to be installed.\n')
} else if (length(to_be_installed) > 0) {
  cat('Some packages already exist; installing remaining packages.\n')
} else {
  cat('All packages installed already!\n')
}

# Install the missing packages
if (length(to_be_installed) > 0) {
  install.packages(to_be_installed, repos = 'https://cloud.r-project.org')
}

cat('\nDone!\n\n')